package com.example.zjsr.common;



import com.example.zjsr.util.JWT;
import net.sf.json.JSONObject;
import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.ByteArrayRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;

import java.io.*;
import java.net.URLEncoder;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;


public class Uploader {
    public static Integer upload(String path, String uploadUrl, Long chunkSize) {
        Integer res = 0;
        RandomAccessFile raf = null;
        try
        {
            // 获取目标文件 预分配文件所占的空间 在磁盘中创建一个指定大小的文件  r 是只读
            raf = new RandomAccessFile(new File(path), "r");
            long length = raf.length();//文件的总长度
            System.out.println("file length=" + length);
            int count = (int)(Math.ceil((double)length / (double)chunkSize));//文件切片后的分片数
            /************************** XJWT生成 ***************************/
            long now = System.currentTimeMillis();
            // 替换其中的secret aesKey issueId即可
            JWT jwt = new JWT(Key.SecretKey, Key.AesKey, System.nanoTime(), Key.issuerId);
            //加密
            String json = "SYS";
            ByteBuffer payload = ByteBuffer.allocate(json.length()).order(ByteOrder.BIG_ENDIAN);
            payload.put(json.getBytes()).flip();

            ByteBuffer token = ByteBuffer.allocate(1024);
            jwt.encryptAndSign2(payload, token, now + 5 * 60 * 1000);
            String xjwt = new String(token.array(), token.arrayOffset(), token.remaining());
            System.out.println("Encode token = " + xjwt);
            /************************* XJWT生成完成 *************************/
            HttpClient httpClient = new HttpClient();
            // 当分片大于1时需要使用httpclient返回的cookie
            StringBuffer tmpcookies = new StringBuffer();
            System.out.println("totalChunks=" + count);
            for (int i = 0; i < count; i++)   //最后一片单独处理
            {
                long begin = i * chunkSize;
                long end = ((i + 1) * chunkSize > length) ? length : (i + 1) * chunkSize;
                System.out.println("end=" + end);
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                byte [] buffer = new byte[1024];
                int realLength = 0;
                raf.seek(begin);//将文件流的位置移动到指定begin字节处
                //while(raf.getFilePointer() <= end && (temp = raf.readLine()) != null)
                while(raf.getFilePointer() <= end && (realLength = raf.read(buffer)) > 0)
                {
                    byteArrayOutputStream.write(buffer, 0, realLength);
                }
                // 设置 HttpClient 接收 Cookie,用与浏览器一样的策略
                httpClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
                System.out.println((uploadUrl + "?chunkSize=" + chunkSize + "&totalChunks=" + count + "&current=" + i + "&xjwt=" + URLEncoder.encode(xjwt) + "&filename=" + URLEncoder.encode((new File(path)).getName())));
                PostMethod pm = new PostMethod(uploadUrl + "?chunkSize=" + chunkSize + "&totalChunks=" + count + "&current=" + i + "&xjwt=" + URLEncoder.encode(xjwt) + "&filename=" + URLEncoder.encode((new File(path)).getName(), "UTF-8"));
                RequestEntity requestEntity = new ByteArrayRequestEntity(byteArrayOutputStream.toByteArray());
                pm.setRequestEntity(requestEntity);
                pm.setRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36");
                pm.setRequestHeader("Content-type", "application/octet-stream; charset=UTF-8");
                int statusCode = httpClient.executeMethod(pm);
                String resp = pm.getResponseBodyAsString();
                System.out.println(resp);
                if(i == count-1 ){
                    JSONObject jsonObject=JSONObject.fromObject(resp);
                    Integer id = Integer.parseInt((String)jsonObject.get("id"));
                    res = id;
                    System.out.println("--->" + id);
                }
                // 获取返回的cookie
                if (statusCode == 200 && i == 0 && count > 1)
                {
                    Cookie[] cookies = httpClient.getState().getCookies();
                    for (Cookie c : cookies)
                    {
                        tmpcookies.append(c.toString() + ";");
                        System.out.println("cookies = " + c.toString());
                    }
                    pm.setRequestHeader("cookie", tmpcookies.toString());
                }

            }
        }
        catch (FileNotFoundException e)
        {
            System.out.println("没有找到文件");
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                File f = new File(path);
                f.delete();
                raf.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
        return res;
    }
    public static void main(String[] args) throws IOException {
        upload("E:\\test.xlsx","http://www.ilab-x.com/project/log/attachment/upload",1048576L);
    }
}
